<!-- 装置激活 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0">
      <div style="">
        <div class="btn topSubmitBtn" style="display: flex; justify-content: flex-end">
          <div style="display: flex; justify-content: space-between; width: 100%">
            <div class="title">
              网络审核参数设置（请勿使用海外代理服务器，如果您不清楚哪些是海外服务器请联系供应商）
            </div>
            
          </div>
        </div>
        <div class="input-item">
          <div class="parawidthmeType">
            <div class="content">
              <div class="setUp">
                  <div>
                <!-- <el-button type="primary" @click="urlCrease()" >使用URL导入</el-button> -->
                <el-button type="primary" @click="increase()" >新增服务器</el-button>
                <el-button type="primary" @click="testMultipleServers()">批量测试连接</el-button>
              </div>
                <!-- <svg-icon icon-class="shezhi" /> -->
                <p>
                  系统采用正向代理模式来进行企业上网行为控制，由于涉及到上网代理功能，请不要使用国外服务器代理进行特殊代理上网。对于禁止的网站，请在"加速审计/域名阻断"对应界面配置策略
                </p>
              </div>
              <el-table stripe  :data="nodeList" style="width: 100%; margin-top: 15px">
              <el-table-column label="批量测试" width="100" align="center">
                <template #default="{ row }">
                  <el-checkbox v-model="row.isSelected" @change="handleSelectionChange(row)" />
                </template>
              </el-table-column>
                <el-table-column label="序号" width="60" type="index" :index="(index) => { return index + 1 + (this.pageNum - 1) * this.pageSize; } ">
                </el-table-column>
                <el-table-column label="服务器名称" show-overflow-tooltip prop="SerName" align="left"></el-table-column>
                <el-table-column label="服务器地址" show-overflow-tooltip prop="IP" align="left"></el-table-column>
                <el-table-column label="状态" show-overflow-tooltip  align="left">
                  <template #default="{ row }">
                    <span v-if="row.loading" class="el-icon-loading"></span>
                    <span v-else>
                      {{ row.status }}
                    </span>
                  </template>
                </el-table-column> 
                <!-- <el-table-column label="认证ID" show-overflow-tooltip prop="Id" align="left"></el-table-column>
                <el-table-column label="认证路径" show-overflow-tooltip prop="Path" align="left"></el-table-column>
                <el-table-column label="本地端口" show-overflow-tooltip prop="Port" width="100px" align="left"></el-table-column>
                <el-table-column label="交互ID" show-overflow-tooltip prop="AlterId" width="150px" align="left"></el-table-column> -->
                <el-table-column label="操作" align="left" width="170px">
                  <template slot-scope="scope">
                    <!-- <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button> -->
                    <el-button size="mini" type="danger" @click="deleteServer(scope.row)">删除</el-button>
                    <el-button size="mini" type="primary" @click="testServer(scope.row)">连接测试</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="使用URL导入" :visible.sync="urlVisible"
      v-el-drag-dialog width="45%">
      <!-- :model="deviceUrl" ref="deviceUrl" -->
      <el-form label-width="120px" label-height="430px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="URL链接:" prop="tag">
              <el-input type="textarea" :rows="6" v-model="deviceUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addURL()">确 定</el-button>
        <el-button type="info" @click="concelUrl()">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="新增服务器" :visible.sync="dialogVisible"
      v-el-drag-dialog width="calc(40% - 4px)">
      <!--顶部分割线 -->
        <el-divider content-position="left">基本信息</el-divider>
      <div class="rule-container">
      <el-form  label-width="120px" :model="deviceForm" :rules="rules" ref="deviceForm">
        <el-row class="rule-content">
          <el-col :span="24">
            <el-form-item label="服务器名称:" prop="SerName">
              <el-input v-model="deviceForm.SerName" maxlength="30" :disabled="Action === 2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务器地址:" prop="IP">
              <el-input v-model="deviceForm.IP" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="端口:" prop="Port">
              <el-input v-model="deviceForm.Port" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="5"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="ssh用户名:" prop="UserName">
              <el-input v-model="deviceForm.UserName" oninput="value=value.replace(/[^0-9a-z_-]/g,'')"
                maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="ssh用户密码:" prop="Passwd">
              <el-input v-model="deviceForm.Passwd" oninput="value=value.replace(/[\u4e00-\u9fa5\r\t\s]/g,'')"
                maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          
        </el-row>
        
      </el-form>
      </div>
      <!--底部分割线 -->
        <el-divider class="lineToFooter"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addServer()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { connrequest } from "@/api/firstPage";
import { parseTime, formatTime } from "@/utils/index.js";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { dealURL } from "@/utils/dealV2rayURL.js";
export default {
  directives: { elDragDialog },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      urlVisible: false,
      dialogVisible: false,
      deviceForm: {},
      Days: 0,
      dayColor: "#67C23A",
      Right: ["0", "0", "0", "0", "0", "0"],
      nodeList: [],
      // list:[],
      rules: {},
      deviceUrl: "",
      tit: "",
      Item: [],
      tagList: [],//存储需要测试的所有IP
      control: false,
      Form: { control: false },
      isCalling: false,
      Action: 1,
      isChecked: false,
      lable: false
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.Right = Cookies.get("Right").split("");
  },
  methods: {
    concelUrl() {
      this.urlVisible = false;
      this.deviceUrl = "";
    },
    async getData() {
      const res = await connrequest("GetV2raySer");
      this.nodeList = res.Data.map(item => ({
        ...item,
        status: '请先进行连接测试',
        isSelected: false,
        loading: false
      }));
      
      
    },
    urlCrease() {
      this.Action = 1;
      this.urlVisible = true;
    },
    increase() {
      this.Action = 1;
      this.dialogVisible = true;
      this.deviceForm = {};
    },
    changeClick(row, i) {
      this.Action = 2;
      // this.Action = row.ShadowLocalPort
      this.dialogVisible = true;
      this.deviceForm = { ...row };
    },
    // 遇相同服务器名执行该函数
    async addItem() {
      // this.contrue = true
      const data = {
        Data: {
          Action: 2,
          Detail: this.Item
        }
      };
      const res = await connrequest("EditV2rayCfg", data);
      if (res.Status.StatusCode === 0) {
        this.$message.success("保存成功");
        this.deviceUrl = "";
        this.getData();
      }
    },
    handleCheckboxChange(value) {
      this.isChecked = value;
    },
    // 链接导入执行该函数
    async addURL() {
      // 解析出来的数据放入到lists
      this.requestArray = dealURL(this.deviceUrl);
      // 重置索引
      this.currentIndex = 0;
    },
    async addServer() {
      let character64 = /^.{1,64}$/;
      let number = /^[0-9]*$/;
      if (!this.deviceForm.SerName) {
        this.$message.error("服务器名称不能为空");
        return false;
      }
      let row = this.nodeList.findIndex(item => item.SerName === this.deviceForm.SerName)
      if (row !== -1 && this.Action !== 2) {
        this.$message.error("服务器名称不能重复");
        return false;
      }
      if (!this.deviceForm.IP) {
        this.$message.error("服务器地址不能为空");
        return false;
      }
      if (
        !character64.test(this.deviceForm.Server) &&
        this.deviceForm.Server !== ""
      ) {
        this.$message.error("服务器地址不能超过64位字符");
        return false;
      }
      if (!this.deviceForm.Port) {
        this.$message.error("本地端口不能为空");
        return false;
      }
      if (
        !number.test(this.deviceForm.Port) ||
        this.deviceForm.Port * 1 > 65535
      ) {
        this.$message.error("本地端口只能填1~65535的数字");
        return false;
      }
      if (!this.deviceForm.UserName) {
        this.$message.error("ssh用户名不能为空");
        return false;
      }
      if (!character64.test(this.deviceForm.UserName) && this.deviceForm.UserName !== "") {
        this.$message.error("ssh用户名不能超过64位字符");
        return false;
      }
      if (!this.deviceForm.Passwd) {
        this.$message.error("ssh用户密码不能为空");
        return false;
      }
      if (!character64.test(this.deviceForm.Passwd)) {
        this.$message.error("ssh用户密码不能超过64位字符");
        return false;
      }
      const data = {
        Data: {
          ...this.deviceForm
        }
      };
      
      const res = await connrequest("AddV2raySer", data);
      if (res.Status.StatusCode === 0) {
        this.dialogVisible = false;
        this.$message.success("保存成功");
        this.getData();
      }
    },
    handleSelectionChange(row) {
        if (row.isSelected) {
        // 如果选中，将IP添加到tagList（避免重复）
        if (!this.tagList.includes(row.SerName)) {
          this.tagList.push(row.SerName);
        }
        } else {
          // 如果取消选中，从tagList中移除IP
          this.tagList = this.tagList.filter(SerName => SerName !== row.SerName);
        }
       
    },
   async testMultipleServers() {
      const selectedNodes = this.nodeList.filter(node => node.isSelected);
      if (!selectedNodes.length) {
        this.$message.warning('请先选择要测试的服务器！');
        return;
      }
      this.$message.success("已开始批量测试,请耐心等待勿离开当前界面")
      try {
         
        // 按顺序执行请求
        const results = [];
        for (const node of selectedNodes) {
          this.$set(node, 'loading', true);
          this.$set(node, 'status', '测试中...');
          const data = {
            Data: {
              Tag: node.SerName
            }
          };
          try {
            const res = await connrequest("TestV2rayNode", data);
            const result = {
              ip: node.SerName,
              status: res.Data.RTime === 0 ? 'failed' : 'success',
              response: res.Data
            };
            results.push(result);

            // 立即更新当前节点状态
            this.$set(node, 'status', result.status === 'success' ? 
              `连接成功${result.response.RTime ? ` (延迟: ${result.response.RTime}ms)` : ''}` : 
              '连接失败');
            this.$set(node, 'loading', false);
            this.$set(node, 'isSelected', false);
          } catch (error) {
            const result = {
              ip: node.SerName,
              status: 'error',
              error: error.message
            };
            results.push(result);

            // 立即更新当前节点状态
            this.$set(node, 'status', `测试错误: ${error.message}`);
            this.$set(node, 'loading', false);
            this.$set(node, 'isSelected', false);
          }
        }

        // （可选）如果你仍需要统计成功/失败数量并显示总结提示，可以取消注释以下代码
        /*
        // 统计成功/失败数量
        const successCount = results.filter(r => r.status === 'success').length;
        const failureCount = results.length - successCount;

        // 显示总结提示
        if (successCount === results.length) {
          this.$message.success(`所有 ${successCount} 个服务器测试成功`);
        } else if (failureCount === results.length) {
          this.$message.error(`所有 ${failureCount} 个服务器测试失败`);
        } else {
          this.$message.warning(`测试完成：${successCount} 个成功，${failureCount} 个失败`);
        }

        // 打印详细日志
        const messages = results.map(r => 
          `IP ${r.ip}: ${r.status === 'success' ? 
          `测试成功 (延迟: ${r.response.RTime || '未知'}ms)` : 
          `测试失败 (${r.status === 'failed' ? 'RTime=0' : r.error})`}`);
        console.log(messages.join('\n'));
        */

  } catch (error) {
    // 全局错误处理（虽然在逐一请求中不太可能触发，但在循环外保留以防万一）
    selectedNodes.forEach(node => {
      this.$set(node, 'loading', false);
      this.$set(node, 'status', `测试错误: ${error.message}`);
    });
    this.$message.error('批量测试失败: ' + error.message);
  }
},
    deleteServer(row) {
      this.$confirm("此操作将删除该服务器, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const data = {
            Data: {
              SerName: row.SerName
            }
          };
          const res = await connrequest("DelV2raySer", data);
          if (res.Status.StatusCode === 0) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async testServer(row) {
      
      // 设置加载状态
    this.$set(row, 'loading', true);
    this.$set(row, 'status', '测试中...'); // 可选：显示“测试中”文本
      const data = {
        Data: {
            Tag : row.SerName
        }
      };
      const res = await connrequest("TestV2rayNode",data);
      // 更新状态和加载标志
      
      this.$set(row, 'loading', false);
      if(res.Data.RTime === 0 )
      {
        this.$set(row, 'status', "连接失败");
      }
      else {
        this.$set(row, 'status', `连接成功(延迟: ${res.Data.RTime}ms)`);
      }
      
    }
  }
};
</script>
<style lang="scss" scoped>
.parameType {
  flex-direction: column;
  margin: 10px 0;
  padding-bottom: 0;
}

.content {
  position: relative;
  margin: 5px 0;
  display: flex;
  flex-wrap: wrap;

  svg {
    font-size: 40px !important;
    margin-right: 20px;
  }

  ::v-deep .certification {
    .el-form-item {
      margin-bottom: 0;
    }

    .el-col {
      width: 1000px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      p {
        display: block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }

  .setUp {
    display: flex;
    align-items: flex-start;
    width: 100vw;
    // margin-bottom: 20px;
    flex-grow: 1;
    flex-direction: column;

    i {
      margin-right: 20px;
    }

    p {
      font-size: 14px;
      color: red;
    }
  }

  .btn {
    position: absolute;
    right: 50px;
    bottom: 20px;
  }
}

.top1 {
  flex-wrap: nowrap;
  // margin-bottom: 20px;
}

::v-deep.el-form-item {
  margin-bottom: 10px;

  label {
    font-weight: 500;
  }
}
.night{
  .setUp {
    p {
      color: #409eff;
    }
  }
}

</style>
